<template>
  <div>
    <a-upload list-type="picture-card" :file-list="fileList" @change="handleChange" name="file" :headers="headers"
     @remove="removeFile"
      :before-upload="beforeUpload" :show-upload-list="true" :customRequest="customUpload">
      <div v-if="fileList.length < maxCount">
        <!-- <plus-outlined /> -->
        <div style="margin-top: 8px">上传</div>
      </div>
    </a-upload>
  </div>
</template>

<script setup>
import { ref ,computed} from 'vue';
import { message } from 'ant-design-vue';
import { baseRequestClient, requestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';

const props = defineProps({
  // 最大上传数量
  maxCount: {
    type: Number,
    default: 1
  },
  // 默认文件列表
  modelValue: {
    type: String,
    default: () => ''
  },
  success:{
    type:Function
  }
});

const emit = defineEmits(['update:modelValue', 'success']);

// 获取 token
const accessStore = useAccessStore();
const headers = {
  Authorization: 'Bearer ' + accessStore.accessToken
};

// 当前文件列表
const fileList = computed(() => {
  return props.modelValue ? [{ url: props.modelValue }] : [];
});

// 文件上传之前校验
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
  if (!isValidType) {
    message.error('只能上传 JPG/PNG/GIF 格式的图片');
    return false; // 阻止默认上传
  }

  const isValidSize = file.size / 1024 / 1024 < 2; // 小于 2MB
  if (!isValidSize) {
    message.error('图片大小不能超过 2MB');
    return false;
  }

  return true;
};

// 自定义上传函数（API 模式）
const customUpload = async ({ file, onProgress, onSuccess, onError }) => {
  const formData = new FormData();
  formData.append('file', file);

  try {
    onProgress({ percent: 30 });

    const response = await requestClient.post('/upload/img', formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        onProgress({ percent });
      }
    });

    onProgress({ percent: 100 });
    const fileName = response.fileName;

    // 构造完整的 URL
    const url = '/api' + fileName;
    fileList.value = [{ url: url }];
    emit('update:modelValue', url);
    emit('success', fileName); // 通知父组件上传成功
    if(props.success instanceof Function){
       props.success(url)
    }
  } catch (error) {
    onError(error);
    message.error('上传出错');
  }
};

const removeFile=()=>{
     fileList.value = [];
    emit('update:modelValue', '');
}

// 文件状态改变事件
const handleChange = ({ file, fileList: newFileList }) => {

};
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
